<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .a.active {
            color: red;
        }

        .a {
            color: blue;
            font-size: 100px;
        }

    </style>
</head>
<body>
    <div class="a">hello world</div>
    <div class="a">hello world</div>
    <div class="a">hello world</div>
    <div class="a">hello world</div>
    <div class="a active">hello world</div>

    <script src="../lib/jquery.min.js"></script>
    <script>

        // w-plan
        // function addClass (selector, className) {
        //     const elements = document.querySelectorAll(selector);
        //     for (const el of elements) {
        //         const oldClassName = el.getAttribute('class'); // 'a'
        //         el.setAttribute('class', `${oldClassName} ${className}`);
        //     }
        // }

        // addClass('.a', 'active');

        // function toggleClass (selector, className) {
        //     const elements = document.querySelectorAll(selector);
        //     for (const el of elements) {
        //         // 获取旧类名 'a active' >>> 'a'
        //         const oldClassName = el.getAttribute('class');
        //         // 把旧类名变成数组方便筛选
        //         const classNames = oldClassName.split(' '); // ['a', 'active', 'active']

        //         if (oldClassName.includes(className)) {
        //             // 1. 去掉classNames数组中的className
        //             const usefulClassNames = classNames.filter((item) => item !== className);
        //             // 2. 把数组用空格拼成字符串用于新类名
        //             el.setAttribute('class', usefulClassNames.join(' '));
        //         } else {
        //             el.setAttribute('class', `${oldClassName} ${className}`);
        //         }
        //     }
        // }

        // toggleClass('.a', 'active');

        // w-plan
        function css (selector, cssObj) {
            const elements = document.querySelectorAll(selector);
            for (const el of elements) {
                // css对象转style字符串
                el.setAttribute('style', css2style(cssObj));
            }
        }

        css('.a', {
            'color': 'pink',
            'background-color': 'blue',
        });

        const obj = {
            'color': 'red',
            'background-color': 'red',
        };

        const expect = 'color: red; background-color: red;';

        function css2style (cssObj) {
            let style = '';
            for (const key in cssObj) {
                const value = cssObj[key];
                style += `${key}: ${value};`; // 'color: red;'
            }
            return style;
        }

        console.log(css2style(obj));


    </script>
</body>
</html>